#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年2月22日

@author: Administrator
'''
from attachment import settings
from attachment.models import Attachment
from attachment.utils import upload_image, upload_file
from common.utils import tool
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.http.response import HttpResponse
import copy
import ujson as json


@login_required
def upload(request):
    u"""
                    文件上传
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    rsp_data["data"] = {}
    optimize = bool(int(request.POST.get('optimize', 0)))
    user_id = request.session[auth.SESSION_KEY]
    # 默认值text,app接口需要返回json数据时可以传值：json
    data_type = request.POST.get('data_type', 'text')
    if request.method == 'POST':
        upfile = request.FILES['upfile']
    elif request.method == 'FILES':
        upfile = request.FILES['upfile']
    else:
        rsp_data = copy.copy(settings.ERROR['ERROR'])
        return HttpResponse(json.dumps(rsp_data), content_type='text/html')
    #文件内容
    file_content = upfile.read()
    #文件后缀
    suffix = tool.image_suffix(upfile.name)
    #保存记录
    attachment = Attachment.objects.create(user_id=user_id,
                   name=upfile.name[0:64], # 此处由于name字段最大长度只有64
                   suffix=suffix,
                   type=1)
    if suffix in settings.ATTACHMENT_IMAGE_SUFFIX_CHOICES: 
        #上传图片
        fpath, width, height = upload_image(file_content, suffix, optimize)
        attachment.fpath = fpath
        attachment.width = width
        attachment.height = height
        attachment.type = 1
        attachment.save()
    else:
        #上传文件
        fpath = upload_file(file_content, suffix)
        attachment.fpath = fpath
        attachment.type = 2
        attachment.save()
        
    rsp_data["data"] = {
        'id': attachment.id,
        'name': attachment.name,
        'fpath': attachment.fpath,
        'url': attachment.absolute_url(),
        "type":attachment.type,
    }
    # 此处content_type必须为text/html, 而不能为application/json
    # 是为了兼容ie下将json格式直接当成下载的情况
    if data_type == 'json':
        return HttpResponse(json.dumps(rsp_data), content_type='application/json')
    return HttpResponse(json.dumps(rsp_data), content_type='text/html')
